import logging
import os
import sys
from logging.handlers import RotatingFileHandler

from .config import settings

# 确保日志目录存在
log_dir = os.path.dirname(settings.LOG_FILE)
if not os.path.exists(log_dir):
    os.makedirs(log_dir)

# 配置日志格式
formatter = logging.Formatter(
    "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"
)

# 控制台日志处理器
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(formatter)

# 文件日志处理器
file_handler = RotatingFileHandler(
    settings.LOG_FILE, maxBytes=10485760, backupCount=10
)  # 10MB per file, keep 10 files
file_handler.setFormatter(formatter)


def get_logger(name: str) -> logging.Logger:
    """获取配置好的日志记录器"""
    logger = logging.getLogger(name)
    
    # 设置日志级别
    log_level = getattr(logging, settings.LOG_LEVEL)
    logger.setLevel(log_level)
    
    # 添加处理器
    logger.addHandler(console_handler)
    logger.addHandler(file_handler)
    
    return logger


# 默认记录器
logger = get_logger("wechat_assistant")